package com.intertid.mongodb
import scala.reflect.BeanProperty
import com.mongodb.DBObject
import com.mongodb.BasicDBObject
import error.MongoDBException
import com.intertid.mongodb.error.MongoDBErrorDefine
import org.apache.commons.lang.StringUtils
import com.intertid.mongodb.annotations.Entity
import com.mongodb.DBRef
import factory.MongoDBTemplateFactory
import net.sf.cglib.proxy.Enhancer
import net.sf.cglib.proxy.Proxy

class RefBean {

  private var $id: Object = _;

  @BeanProperty
  var className: String = _;

  def `set$id`(id: Object) = { $id = id; }

  def `get$id`(): Object = $id;

  @BeanProperty
  var souce: Object = _;

  @BeanProperty
  var dbref: DBRef = _;

  //  def toDBObject(): DBObject = {
  //    val dbobj = new BasicDBObject;
  //    dbobj.put("id", $id);
  //    dbobj.put("className", className);
  //    val classz = Class.forName(className);
  //    if (!classz.isAnnotationPresent(classOf[Entity])) {
  //      throw new MongoDBException(MongoDBErrorDefine.ENTITY_DEFINE_NOT_FOUND);
  //    } else {
  //      val entity = classz.getAnnotation(classOf[Entity]);
  //      dbobj.put("$ref", if (StringUtils.isEmpty(entity.name())) classz.getSimpleName() else entity.name());
  //    }
  //    dbobj
  //  }

  def toDBObject(): DBRef = {
    val name = Mapper.getCollectionName(Class.forName(className))
    println("-->" + $id);
    val dbref = new DBRef(MongoDBTemplateFactory.getCurrentTemplate().session.underlying, name, $id);
    return dbref;
  }
}